package self.hoy.demo.grainmall.product.service.impl;

import com.baomidou.dynamic.datasource.annotation.DS;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.stereotype.Service;

import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import self.hoy.demo.common.utils.PageUtils;
import self.hoy.demo.common.utils.Query;

import self.hoy.demo.grainmall.product.entity.SkuImages;
import self.hoy.demo.grainmall.product.entity.SpuInfoDesc;
import self.hoy.demo.grainmall.product.mapper.SkuInfoMapper;
import self.hoy.demo.grainmall.product.entity.SkuInfo;
import self.hoy.demo.grainmall.product.service.*;
import self.hoy.demo.grainmall.product.vo.SkuItemSaleAttrVo;
import self.hoy.demo.grainmall.product.vo.SkuItemVo;
import self.hoy.demo.grainmall.product.vo.SpuItemAttrGroupVo;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoMapper, SkuInfo> implements SkuInfoService {

    @Autowired
    private SkuImagesService imagesService;

    @Autowired
    private ThreadPoolExecutor executor;

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfo> page = this.page(
                new Query<SkuInfo>().getPage(params),
                new QueryWrapper<SkuInfo>()
        );

        return new PageUtils(page);
    }

    //key:
    //catelogId: 0
    //brandId: 0
    @Override
    public PageUtils queryPageByConditions(Map<String, Object> params) {
        QueryWrapper<SkuInfo> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and(w -> w.eq("sku_id", key).or().like("sku_name", key));
        }
        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equals(brandId)) {
            wrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equals(catelogId)) {
            wrapper.eq("catelog_id", catelogId);
        }

        String min = (String) params.get("min");
        if (!StringUtils.isEmpty(min)) {
            wrapper.ge("price", min);
        }

        String max = (String) params.get("max");
        if (!StringUtils.isEmpty(max) && !"0".equals(max)) {
            wrapper.le("price", max);
        }

        IPage<SkuInfo> page = this.page(
                new Query<SkuInfo>().getPage(params), wrapper
        );
        return new PageUtils(page);
    }

    @Override
    public List<SkuInfo> getSkusBySpuId(Long spuId) {
        return this.list(
                new QueryWrapper<SkuInfo>().eq("spu_id", spuId )
        );
    }

    /**
     * 使用异步编排优化查询性能
     * @param skuId
     * @return
     */
    @Override
    @DS("slave")
    public SkuItemVo item(Long skuId) throws ExecutionException, InterruptedException {
        SkuItemVo skuItemVo = new SkuItemVo();

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
//        2、sku的图片信息
            List<SkuImages> images = imagesService.getImagesBySkuId(skuId);
            skuItemVo.setImages(images);
        }, executor);

        CompletableFuture<SkuInfo> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
//        1、sku基本信息 pms_sku_info
            SkuInfo info = getById(skuId);
            skuItemVo.setInfo(info);
            return info;
        }, executor);

        CompletableFuture<Void> saleAttrFuture = skuInfoFuture.thenAcceptAsync(info -> {
//        3、spu的销售属性组合
            List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(info.getSpuId());
            skuItemVo.setSaleAttr(saleAttrVos);
        }, executor);

        CompletableFuture<Void> descFuture = skuInfoFuture.thenAcceptAsync(info -> {
//        4、spu介绍
            SpuInfoDesc spuInfoDesc = spuInfoDescService.getById(info.getSpuId());
            skuItemVo.setDesp(spuInfoDesc);
        }, executor);

        CompletableFuture<Void> baseAttrFuture = skuInfoFuture.thenAcceptAsync(info -> {
//        5、spu的规格参数
            List<SpuItemAttrGroupVo> groupAttrs =
                    attrGroupService.getAttrGroupWithAttrsBySpuId(info.getSpuId(), info.getCatalogId());
            skuItemVo.setGroupAttrs(groupAttrs);
        }, executor);

        //等待所有任务都完成
        CompletableFuture.allOf(saleAttrFuture, descFuture, baseAttrFuture, imageFuture).get();

        return skuItemVo;
    }

    @Override
    @DS("slave")
    public SkuItemVo itemNoFuture(Long skuId) {
        SkuItemVo skuItemVo = new SkuItemVo();
//        1、sku基本信息 pms_sku_info
        SkuInfo info = getById(skuId);
        skuItemVo.setInfo(info);
        Long spuId = info.getSpuId();
        Long catalogId = info.getCatalogId();

//        2、sku的图片信息
        List<SkuImages> images = imagesService.getImagesBySkuId(skuId);
        skuItemVo.setImages(images);

//        3、spu的销售属性组合
        List<SkuItemSaleAttrVo> saleAttrVos = skuSaleAttrValueService.getSaleAttrsBySpuId(spuId);
        skuItemVo.setSaleAttr(saleAttrVos);

//        4、spu介绍
        SpuInfoDesc spuInfoDesc = spuInfoDescService.getById(spuId);
        skuItemVo.setDesp(spuInfoDesc);

//        5、spu的规格参数
        List<SpuItemAttrGroupVo> groupAttrs = attrGroupService.getAttrGroupWithAttrsBySpuId(spuId, catalogId);
        skuItemVo.setGroupAttrs(groupAttrs);

        return skuItemVo;
    }

    @Override
    public void saveSkuInfo(SkuInfo skuInfo) {
        baseMapper.insert(skuInfo);
    }

}